/**
 * Copyright (c) 2015 www.smarthome.com All rights reserved. <br />
 * 本软件源代码版权归xxxx公司,未经许可不得任意复制与传播.<br />
 *
 */
package com.smarthome.core.user.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.smarthome.base.service.ShUserResourceService;
import com.smarthome.core.user.UserResourceService;
import com.smarthome.domain.bean.ShUser;
import com.smarthome.domain.bean.ShUserResource;
import com.smarthome.domain.enums.ShUserResourceOpenFlagEnum;
import com.smarthome.domain.enums.ShUserResourceTypeFlagEnum;
import com.smarthome.domain.enums.ShUserSuperFlagEnum;
import com.smarthome.domain.vo.boss.Tree;

@Service("userResourceService")
public class UserResourceServiceImpl implements UserResourceService {

    protected static Logger LOGGER;

    @Resource
    private ShUserResourceService shUserResourceService;

    public UserResourceServiceImpl() {
        LOGGER = LoggerFactory.getLogger(this.getClass());
    }

    @Override
    public List<ShUserResource> queryAllOpenedUserResources() {
        return shUserResourceService.queryAllOpenedUserResources();
    }

    @Override
    public ShUserResource queryUserResourceById(Long id) {
        ShUserResource shUserResource = shUserResourceService.selectEntryById(id);
        if (null != shUserResource.getParentId() && 0L != shUserResource.getParentId()) {
            ShUserResource shUserResourceParent = shUserResourceService.selectEntryById(shUserResource.getParentId());
            shUserResource.setParentResource(shUserResourceParent);
        }
        return shUserResource;
    }

    @Override
    public List<ShUserResource> queryUserResourcesByUserId(Long userId) {
        return shUserResourceService.queryUserResourcesByUserId(userId);
    }

    @Override
    public List<ShUserResource> queryUserResourcesByUserAndRole(Long userId, Long residenceId) {
        return shUserResourceService.queryUserResourcesByUserAndRole(userId, residenceId);
    }

    @Override
    public List<Tree> tree(ShUser shUser, ShUserResourceTypeFlagEnum type) {
        List<ShUserResource> currentShUserResources = new ArrayList<ShUserResource>();
        if (null == shUser || (shUser.getSuperFlag() == ShUserSuperFlagEnum.SUPER.getFlag())) {// 超级管理员默认拥有所有操作权限
            currentShUserResources = queryAllOpenedUserResources();
        } else {
        	/***edit by dhc 2015/10/13*/
           // currentShUserResources = queryUserResourcesByUserId(shUser.getId());
            currentShUserResources = queryUserResourcesByUserAndRole(shUser.getId(),shUser.getCurrentResidence().getId());
        }
        return generateMenuTree(currentShUserResources, 0L, type);
    }

    private List<Tree> generateMenuTree(List<ShUserResource> shUserResources, Long parentId, ShUserResourceTypeFlagEnum type) {
        List<Tree> trs = new ArrayList<Tree>();
        for (ShUserResource shUserResource : shUserResources) {
            if (null != type && shUserResource.getTypeFlag() != type.getFlag()) {
                continue;
            }
            if (parentId == shUserResource.getParentId()) {
                Tree tr = new Tree();
                tr.setId(shUserResource.getId());
                tr.setPid(shUserResource.getParentId());
                tr.setIconCls(shUserResource.getIconPath());
                tr.setText(shUserResource.getName());
                Map<String, Object> attr = new HashMap<String, Object>();
                attr.put("url", shUserResource.getAddress());
                tr.setAttributes(attr);
                tr.setChildren(generateMenuTree(shUserResources, shUserResource.getId(), type));
                trs.add(tr);
            }
        }
        return trs;
    }

    @Override
    public List<ShUserResource> treeGrid(ShUser shUser) {
        List<ShUserResource> currentShUserResources = new ArrayList<ShUserResource>();
        if (null == shUser || (shUser.getSuperFlag() == ShUserSuperFlagEnum.SUPER.getFlag())) {// 超级管理员默认拥有所有操作权限
            currentShUserResources = queryAllOpenedUserResources();
        } else {
            currentShUserResources = queryUserResourcesByUserId(shUser.getId());
        }

        List<ShUserResource> allShUserResources = queryAllOpenedUserResources();
        Map<Long, ShUserResource> rsMap = new HashMap<Long, ShUserResource>();
        for (ShUserResource rs : allShUserResources) {
            rsMap.put(rs.getId(), rs);
        }
        for (ShUserResource rs : currentShUserResources) {
            if (null != rs.getParentId() && 0L != rs.getParentId()) {
                rs.setParentResource(rsMap.get(rs.getParentId()));
            }
        }
        return currentShUserResources;
    }

    @Override
    public void edit(ShUserResource resource) {
        ShUserResource shUserResource = shUserResourceService.selectEntryById(resource.getId());
        if (shUserResource != null) {
            // TODO 需要判断当前资源是否修改到当前资源的子/孙子资源下
            BeanUtils.copyProperties(resource, shUserResource);
            shUserResourceService.saveOrUpdate(shUserResource);
        }
    }

    @Override
    public void add(ShUserResource resource) {
        shUserResourceService.saveOrUpdate(resource);
        // TODO 由于当前用户所属的角色，没有访问新添加的资源权限，所以在新添加资源的时候，将当前资源授权给当前用户的所有角色，以便添加资源后在资源列表中能够找到
    }

    @Override
    public void delete(Long id) {
        // List<ShUserResource> allShPropertyRoles = queryAllChildrens(queryAllOpenedUserResources(), id);
        // for (ShUserResource shUserResource : allShPropertyRoles) {
        // shUserResource.setOpenFlag(ShUserResourceOpenFlagEnum.CLOSE.getFlag());
        // shUserResourceService.saveOrUpdate(shUserResource);
        // }
        // ShUserResource shUserResource = new ShUserResource();
        // shUserResource.setOpenFlag(ShUserResourceOpenFlagEnum.CLOSE.getFlag());
        ShUserResource shUserResource = queryUserResourceById(id);
        shUserResource.setOpenFlag(ShUserResourceOpenFlagEnum.CLOSE.getFlag());
        shUserResourceService.saveOrUpdate(shUserResource);
        // TODO 删除所有角色资源对照
    }

    private List<ShUserResource> queryAllChildrens(List<ShUserResource> shUserResources, Long parentId) {
        List<ShUserResource> trs = new ArrayList<ShUserResource>();
        for (ShUserResource shUserResource : shUserResources) {
            if (parentId == shUserResource.getParentId()) {
                trs.add(shUserResource);
                trs.addAll(queryAllChildrens(shUserResources, shUserResource.getId()));
            }
        }
        return trs;
    }
}
